package mysql

import (
	"errors"

	"gorm.io/gorm"

	"mxshop_srvs/goods_srv/model"
)

func (g *Gorm) GetBrandsCount() (int64, error) {
	return g.GetModelCount(&model.Brands{})
}

func (g *Gorm) GetBrandList(page, pageSize int) ([]model.Brands, error) {
	var brands []model.Brands
	result := g.db.Scopes(Paginate(page, pageSize)).Find(&brands)
	if err := result.Error; err != nil {
		if errors.Is(err, gorm.ErrRecordNotFound) {
			return brands, nil
		}
		return brands, err
	}
	return brands, nil
}

func (g *Gorm) BrandExistsByName(name string) (bool, error) {
	var count int64
	result := g.db.Model(&model.Brands{}).Where("name=?", name).Count(&count)
	if result.Error != nil {
		return false, result.Error
	}
	if count == 0 {
		return false, nil
	}
	return true, nil
}

func (g *Gorm) CreateBrand(brand *model.Brands) (int32, error) {
	result := g.db.Create(brand)
	return brand.ID, result.Error
}

func (g *Gorm) BrandExistsByID(id int32) (bool, error) {
	var count int64
	result := g.db.Model(&model.Brands{}).Where("id=?", id).Count(&count)
	if result.Error != nil {
		return false, result.Error
	}
	if count == 0 {
		return false, nil
	}
	return true, nil
}

func (g *Gorm) GetBrandByID(id int32) (*model.Brands, error) {
	var brand model.Brands
	result := g.db.First(&brand, id)
	if result.Error != nil {
		return nil, result.Error
	}
	return &brand, nil
}

func (g *Gorm) UpdateBrand(brand *model.Brands) (int64, error) {
	result := g.db.Select("*").Omit("CreatedAt").Updates(brand)
	return result.RowsAffected, result.Error
}

func (g *Gorm) DeleteBrand(id int32) (int64, error) {
	result := g.db.Delete(&model.Brands{}, id)
	return result.RowsAffected, result.Error
}
